<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
            width: 400px;
            height: 400px;
            border: 1px solid #000;
            position: relative;
        }
        span{
            display: none;
           position: absolute;
           top: 0;
           left: 0;
           width: 100px;
           height: 100px;
           background-color: rgb(243, 91, 91);
        }
    </style>
</head>
<body>
    <div class="box">
        <span></span>
    </div>
    <script>
        var div = document.querySelector("div");
        var span = document.querySelector("span");

        // 在鼠标在div上移动时,设置span跟随鼠标移动

        // 1.先给div添加移入事件
        div.onmouseenter = function(){
            // 2.移入后设置span的显示
            span.style.display = "block";
            // 5.在移入后给div添加鼠标移动事件
            div.onmousemove = function(e){
                // 获取鼠标距离当前触发事件标签的位置
                // e.offsetX;
                // e.offsetY;
                // e.layerY; 
                // e.layerY;
                // 获取标签距离浏览器窗口的偏移量
                var x = div.getBoundingClientRect().x;
                var y = div.getBoundingClientRect().y;
                // 鼠标距离浏览器窗口的偏移量 - 标签距离浏览器窗口的偏移量 == 鼠标到标签的偏移量
                var l = e.clientX - x - span.offsetWidth / 2;
                var t = e.clientY - y - span.offsetHeight / 2;

                l = l < 0 ? 0 : l;
                t =  t < 0 ? 0 : t;
                var maxW = div.offsetWidth - span.offsetWidth;
                var maxH = div.offsetHeight - span.offsetHeight;
                l = l > maxW ? maxW : l;
                t = t > maxH ? maxH : t;
                
                span.style.left = l + "px";
                span.style.top = t + "px";
            }
        }
        // 3.给div添加移出事件
        div.onmouseleave = function(){
            // 4.移出时设置span的隐藏
            span.style.display = "none";
            // 6.在鼠标移出div后给div删除鼠标移动事件
            div.onmousemove = null;
        }
        
    </script>
</body>
</html>